package cn.harry.cabinet.view

import android.content.Intent
import android.os.Bundle
import android.view.View
import android.widget.ImageView
import android.widget.TextView
import androidx.appcompat.app.AppCompatActivity
import androidx.cardview.widget.CardView
import androidx.core.content.ContextCompat
import androidx.lifecycle.lifecycleScope
import cn.harry.cabinet.R
import cn.harry.cabinet.theme.manager.ThemeManager
import cn.harry.cabinet.utils.VoiceHelper
import kotlinx.coroutines.Dispatchers
import kotlinx.coroutines.launch
import kotlinx.coroutines.withContext

/**
 * 验证方式选择页面
 * 根据操作类型（还仪器/取仪器）显示不同的验证选项
 */
class AuthMethodSelectionActivity : AppCompatActivity() {
    
    companion object {
        const val EXTRA_ACTION_TYPE = "action_type"
        const val EXTRA_CARD_LABEL = "card_label"
        const val ACTION_RETURN = "return"
        const val ACTION_TAKE = "take"
    }
    
    private lateinit var titleText: TextView
    private lateinit var subtitleText: TextView
    private lateinit var option1Card: CardView
    private lateinit var option2Card: CardView
    private lateinit var option3Card: CardView
    private lateinit var option1Title: TextView
    private lateinit var option2Title: TextView
    private lateinit var option3Title: TextView
    private lateinit var option1Subtitle: TextView
    private lateinit var option2Subtitle: TextView
    private lateinit var option3Subtitle: TextView
    private lateinit var backButton: View
    
    private var actionType: String = ACTION_RETURN
    private var cardLabel: String? = null
    
    override fun onCreate(savedInstanceState: Bundle?) {
        super.onCreate(savedInstanceState)
        setContentView(R.layout.activity_auth_method_selection)
        
        // 获取操作类型和卡片标签
        actionType = intent.getStringExtra(EXTRA_ACTION_TYPE) ?: ACTION_RETURN
        cardLabel = intent.getStringExtra(EXTRA_CARD_LABEL)
        
        // 初始化视图
        initViews()
        
        // 应用主题
        applyTheme()
        
        // 配置界面内容
        setupContent()
        
        // 设置点击事件
        setupClickListeners()
        
        // 播放语音提示
        speakPrompt()
    }
    
    private fun initViews() {
        titleText = findViewById(R.id.tv_auth_title)
        subtitleText = findViewById(R.id.tv_auth_subtitle)
        option1Card = findViewById(R.id.cv_auth_option1)
        option2Card = findViewById(R.id.cv_auth_option2)
        option3Card = findViewById(R.id.cv_auth_option3)
        option1Title = findViewById(R.id.tv_option1_title)
        option2Title = findViewById(R.id.tv_option2_title)
        option3Title = findViewById(R.id.tv_option3_title)
        option1Subtitle = findViewById(R.id.tv_option1_subtitle)
        option2Subtitle = findViewById(R.id.tv_option2_subtitle)
        option3Subtitle = findViewById(R.id.tv_option3_subtitle)
        backButton = findViewById(R.id.btn_back)
    }
    
    /**
     * 播放语音提示
     */
    private fun speakPrompt() {
        VoiceHelper.speakSelectAuthMethod(actionType)
    }
    
    private fun setupContent() {
        when (actionType) {
            ACTION_RETURN -> {
                titleText.text = if (!cardLabel.isNullOrBlank()) {
                    "$cardLabel - 请选择验证方式"
                } else {
                    "请选择验证方式"
                }
                
                // 选项1: 刷卡
                option1Title.text = "刷卡验证"
                option1Subtitle.text = "使用IC卡进行身份验证"
                findViewById<ImageView>(R.id.iv_option1_icon).setImageResource(R.drawable.ic_card)
                
                // 选项2: 输入密码（暂时隐藏）
                option2Card.visibility = View.GONE
                // option2Title.text = "密码验证"
                // option2Subtitle.text = "输入密码进行身份验证"
                // findViewById<ImageView>(R.id.iv_option2_icon).setImageResource(R.drawable.ic_password)
                
                // 选项3: 隐藏（还仪器只有一个选项）
                option3Card.visibility = View.GONE
            }
            ACTION_TAKE -> {
                titleText.text = if (!cardLabel.isNullOrBlank()) {
                    "$cardLabel - 请选择验证方式"
                } else {
                    "请选择验证方式"
                }
                
                // 选项1: 人脸识别
                option1Title.text = "人脸识别"
                option1Subtitle.text = "快速安全的生物识别验证"
                findViewById<ImageView>(R.id.iv_option1_icon).setImageResource(R.drawable.ic_face)
                
                // 选项2: 输入密码（暂时隐藏）
                option2Card.visibility = View.GONE
                // option2Title.text = "密码验证"
                // option2Subtitle.text = "输入密码进行身份验证"
                // findViewById<ImageView>(R.id.iv_option2_icon).setImageResource(R.drawable.ic_password)
                
                // 选项3: 隐藏（取仪器只有一个选项）
                option3Card.visibility = View.GONE
            }
        }
    }
    
    private fun setupClickListeners() {
        // 返回按钮
        backButton.setOnClickListener {
            finish()
        }
        
        // 选项1点击事件
        option1Card.setOnClickListener {
            handleOption1Click()
        }
        
        // 选项2点击事件
        option2Card.setOnClickListener {
            handleOption2Click()
        }
        
        // 选项3点击事件
        option3Card.setOnClickListener {
            handleOption3Click()
        }
    }
    
    private fun handleOption1Click() {
        when (actionType) {
            ACTION_RETURN -> {
                // 刷卡验证 - 跳转到刷卡验证页面
                val intent = Intent(this, CardScanActivity::class.java)
                intent.putExtra(BaseAuthActivity.EXTRA_ACTION_TYPE, BaseAuthActivity.ACTION_RETURN)
                startActivity(intent)
            }
            ACTION_TAKE -> {
                // 人脸识别 - 跳转到人脸识别页面
                val intent = Intent(this, FaceRecognitionActivity::class.java)
                intent.putExtra(BaseAuthActivity.EXTRA_ACTION_TYPE, BaseAuthActivity.ACTION_TAKE)
                startActivity(intent)
            }
        }
    }
    
    private fun handleOption2Click() {
        // 密码验证 - 跳转到密码验证页面
        val intent = Intent(this, PasswordAuthActivity::class.java)
        intent.putExtra(BaseAuthActivity.EXTRA_ACTION_TYPE, 
            if (actionType == ACTION_RETURN) BaseAuthActivity.ACTION_RETURN 
            else BaseAuthActivity.ACTION_TAKE)
        startActivity(intent)
    }
    
    private fun handleOption3Click() {
        // 第三个选项（预留）
        when (actionType) {
            ACTION_RETURN -> {
                // 还仪器的第三个选项
                val intent = Intent(this, ReturnInstrumentActivity::class.java)
                intent.putExtra("auth_method", "option3")
                startActivity(intent)
                finish()
            }
            ACTION_TAKE -> {
                // 取仪器的第三个选项
                val intent = Intent(this, TakeInstrumentActivity::class.java)
                intent.putExtra("auth_method", "option3")
                startActivity(intent)
                finish()
            }
        }
    }
    
    private fun applyTheme() {
        lifecycleScope.launch {
            try {
                val theme = withContext(Dispatchers.IO) {
                    ThemeManager.loadThemeFromDatabase(this@AuthMethodSelectionActivity)
                }
                withContext(Dispatchers.Main) {
                    ThemeManager.applyTheme(this@AuthMethodSelectionActivity, theme)
                    applyAuthPageTheme(theme)
                }
            } catch (e: Exception) {
                val defaultTheme = ThemeManager.getCurrentTheme(this@AuthMethodSelectionActivity)
                ThemeManager.applyTheme(this@AuthMethodSelectionActivity, defaultTheme)
                applyAuthPageTheme(defaultTheme)
            }
        }
    }
    
    private fun applyAuthPageTheme(theme: ThemeManager.Theme) {
        val themeColors = ThemeManager.getThemeColors(theme)
        
        // 更新主背景
        val backgroundDrawable = when (theme) {
            ThemeManager.Theme.CHINA_RED -> ContextCompat.getDrawable(this, R.drawable.china_red_background)
            ThemeManager.Theme.VIBRANT_ORANGE -> ContextCompat.getDrawable(this, R.drawable.vibrant_orange_background)
            ThemeManager.Theme.TECH_BLUE -> ContextCompat.getDrawable(this, R.drawable.tech_blue_background)
        }
        findViewById<View>(R.id.auth_root)?.background = backgroundDrawable
        
        // 更新卡片背景
        val primaryColor = ContextCompat.getColor(this, themeColors.primary)
        val secondaryColor = ContextCompat.getColor(this, themeColors.secondary)
        val accentColor = ContextCompat.getColor(this, themeColors.accent)
        
        option1Card.setCardBackgroundColor(primaryColor)
        option2Card.setCardBackgroundColor(secondaryColor)
        option3Card.setCardBackgroundColor(accentColor)
        
        // 更新图标颜色（使用卡片的主题色）
        findViewById<ImageView>(R.id.iv_option1_icon)?.setColorFilter(primaryColor)
        findViewById<ImageView>(R.id.iv_option2_icon)?.setColorFilter(secondaryColor)
        findViewById<ImageView>(R.id.iv_option3_icon)?.setColorFilter(accentColor)
        
        // 更新文字颜色（标题在顶部标题栏）
        val textColor = ContextCompat.getColor(this, themeColors.onSurface)
        titleText.setTextColor(textColor)
    }
    
    override fun onDestroy() {
        super.onDestroy()
        // 停止语音播放
        VoiceHelper.stop()
    }
}
